package com.bob.demo.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bob.demo.system.dao.MenuRepository;
import com.bob.demo.system.dao.RoleMenuRepository;
import com.bob.demo.system.dao.UserRepository;
import com.bob.demo.system.dao.UserRoleRepository;
import com.bob.demo.system.model.Menu;
import com.bob.demo.system.model.Tree;
import com.bob.demo.system.model.User;
import com.bob.demo.system.service.IUserService;
import com.bob.demo.utils.BuildTree;
import com.bob.demo.utils.StringUtils;

@Service
@Transactional
public class UserServiceImpl implements IUserService {
	@Autowired
    private UserRepository userRepository;
	
	@Autowired
    private RoleMenuRepository roleMenuRepository;
	
	@Autowired
    private MenuRepository menuRepository;
	
	@Override
	public List<Tree<Menu>> listMenuTree(String userId) {
		// TODO Auto-generated method stub
		List<Tree<Menu>> trees = new ArrayList<Tree<Menu>>();
		//获取该用户的所有角色
		//获取所有角色的所有菜单
		List<Menu> menuList = menuRepository.findMenuByUserId(userId);
		for (Menu sysMenu : menuList) {
			Tree<Menu> tree = new Tree<Menu>();
			tree.setId(sysMenu.getId().toString());
			tree.setOpen(sysMenu.isOpen());
			tree.setParentId(sysMenu.getParentId().toString());
			tree.setText(sysMenu.getName());
			Map<String, Object> attributes = new HashMap<>();
			attributes.put("url", sysMenu.getUrl());
			attributes.put("icon", sysMenu.getIcon());
			tree.setAttributes(attributes);
			trees.add(tree);
		}
		// 默认顶级菜单为０，根据数据库实际情况调整
		List<Tree<Menu>> list = BuildTree.buildList(trees, "0");
		return list;
	}

	@Override
	public User save(User user) {
		// TODO Auto-generated method stub
		if(user.getId() == null) {
			user.setId(StringUtils.getUUID());
			user.setCreateTime(new Date());
		}
		userRepository.save(user);
		return user;
	}

	
}
